package com.tem.system.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.tem.common.tool.result.ResultUtil;
import com.tem.system.entity.SysDepartment;
import com.api.manage.pojo.system.SysDepartmentBean;
import com.tem.system.mapper.SysDepartmentMapper;
import com.tem.system.service.ISysDepartmentService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;
/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 腾木
 * @since 2023-11-17
 */
@Service
public class SysDepartmentServiceImpl extends ServiceImpl<SysDepartmentMapper, SysDepartment> implements ISysDepartmentService {
    @Transactional(readOnly = true)
    public List<SysDepartmentBean> queryList(Long sysBranchOfficeId){
        QueryWrapper<SysDepartment> queryWrapper = new QueryWrapper();
        queryWrapper.eq("sys_branch_office_id",sysBranchOfficeId);
        List<SysDepartment> entityList = this.list(queryWrapper);
        // 构建树结构数据返回
        List<SysDepartmentBean> treeEntityList = new ArrayList<>();
        SysDepartmentBean sysDepartmentBean=null;
        if(!CollectionUtils.isEmpty(entityList)){
            for(SysDepartment s:entityList){
                sysDepartmentBean=new SysDepartmentBean();
                BeanUtil.copyProperties(s,sysDepartmentBean);
                treeEntityList.add(sysDepartmentBean);
            }
            treeEntityList =  buildTree(treeEntityList,0L);
        }
        return treeEntityList;
    }
    // 递归
    public static List<SysDepartmentBean> buildTree(List<SysDepartmentBean> list, Long pid){
        List<SysDepartmentBean> children = list.stream().filter(x -> x.getParentId().equals(pid)).collect(Collectors.toList());
        List<SysDepartmentBean> subclass = list.stream().filter(x -> !x.getParentId().equals(pid)).collect(Collectors.toList());
        if(children.size() > 0){
            children.forEach(x -> {
                if(subclass.size() > 0){
                    buildTree(subclass,x.getId()).forEach(
                        y -> x.getChildren().add(y)
                    );
                }
            });
        }
        return children;
    }
}
